import json

from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
# from django import http
from django.http.response import HttpResponse,HttpResponseForbidden, JsonResponse
import re

# Create your views here.
# from apps.users import constants
from apps.users import constants
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from django.contrib.auth.mixins import LoginRequiredMixin

from utils.seceret import SecretOauth

class AddressView(View):
    def get(self,request):
        return render(request,'user_center_site.html')


class VerifyEmailView(View):
    def get(self,request):
        token = request.GET.get('token')
        token_dict = SecretOauth().loads(token)

        try:
            user = User.objects.get(id=token['user_id'],email=token_dict['email'])

        except Exception as e:
            return HttpResponseForbidden('无效的token')
        user.email_active = True
        user.save()

        return redirect(reverse('contents:index'))

class EmailView(LoginRequiredMixin,View):
    def put(self,request):
        email = json.loads(request.body.decode()).get('email')

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.EMAILERR, 'errmsg': '添加邮箱失败'})
        from apps.users.utils import generate_verify_email_url
        verify_url = generate_verify_email_url(request.user)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email,verify_url)

        return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})

class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        context = {
            'username':request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,

        }
        return render(request,'user_center_info.html',context)

class LogoutView(View):
    def get(self,request):
        from django.contrib.auth import logout
        logout(request)

        respose = render(request,'login.html')
        respose.delete_cookie('username')
        return respose

class LoginView(View):
    def get(self,request):
        return render(request,'login.html')

    def post(self, request):
        """
        实现登录逻辑
        :param request: 请求对象
        :return: 登录结果
        """
        # 1.接收三个参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')


        # 2.校验参数
        if not all([username, password]):
            return HttpResponseForbidden('参数不齐全')
        # 2.1 用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        # 2.2 密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')

        # 3.验证用户名和密码--django自带的认证
        from django.contrib.auth import authenticate, login
        user = authenticate(username=username, password=password)

        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        login(request,user)
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('contents:index'))
        response.set_cookie('username',constants.USERNAME_EXPIRE_TIME)
        return response

class MobilesCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','count':count})

class UsernameCountView(View):
    def get(self,request,username):

        from apps.users.models import User
        count = User.objects.filter(username=username).count()
        from utils.response_code import RETCODE
        return JsonResponse({

            "code": '0',
            "errmsg": "ok",
            "count": count,
            })

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        print(request.POST)

        if not all([username,password,password2,mobile,allow]):
            return HttpResponseForbidden('参数不齐！')
        if not re.match('^[a-zA-Z0-9_-]{5,20}$',username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match('^[0-9A-Za-z]{8,20}$',password):
            return HttpResponseForbidden('请输入8-20个字符的密码')
        if password2 !=password:
            return HttpResponseForbidden('两次密码不一致')

        if not re.match('^1[345789]\d{9}$',mobile):
            return HttpResponseForbidden('您输入的手机号格式不正确')

        if allow != 'on':
            return HttpResponseForbidden('请勾选用户协议')


        sms_code = request.POST.get('msg_code')
        from django_redis import get_redis_connection
        redis_code_client = get_redis_connection('sms_code')
        redis_code = redis_code_client.get('sms_%s' % mobile)

        if redis_code is None:
            return render(request,'register.html',{'sms_code_errmsg': '无效的短信验证码'})
        if redis_code.decode() != sms_code:
            return render(request,'register.html',{'sms_code_errmsg': '无效的短信验证码'})

        try:
            from apps.users.models import User
            user = User.objects.create_user(username=username,
                                     password=password,
                                     mobile=mobile)

        except Exception as e:
            logger.error(e)
            return render(request,'register.html',{'register_errmsg':'注册失败'})

        login(request,user)



        response = redirect(reverse('contents:index'))
        response.set_cookie('username', username,max_age=60)

        return response#         接受参数

